package com.the4man.framework.interceptor;

import com.the4man.framework.pagemodel.PPage;
import com.the4man.framework.pagemodel.PageContext;
import com.the4man.framework.util.dialect.DB2Dialect;
import com.the4man.framework.util.dialect.Dialect;
import com.the4man.framework.util.dialect.MysqlDialect;
import com.the4man.framework.util.dialect.OracleDialect;
import com.the4man.framework.utils.InitParamUtil;
import com.the4man.framework.utils.RequestUtil;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.mapping.*;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.mapping.MappedStatement.Builder;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * Created by lenovo on 2017/12/12.
 */
@Intercepts({@Signature(
        type = Executor.class,
        method = "query",
        args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}
)})
public class PaginationInterceptor implements Interceptor {
    private static final Logger logger = LoggerFactory.getLogger(PaginationInterceptor.class);
    Dialect dialect = null;

    public PaginationInterceptor() {
    }

    public void setDialect() {
        if("DB2".equals(InitParamUtil.getDatabaseInfoName())) {
            this.dialect = new DB2Dialect();
        } else if("ORACLE".equals(InitParamUtil.getDatabaseInfoName())) {
            this.dialect = new OracleDialect();
        } else if("MYSQL".equals(InitParamUtil.getDatabaseInfoName())) {
            this.dialect = new MysqlDialect();
        } else {
            this.dialect = new Dialect();
        }

    }

    public Object intercept(Invocation invocation) throws Throwable {
        if(RequestUtil.getUserSessionObject() == null) {
            return invocation.proceed();
        } else {
            String sqlID = null;
            MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
            sqlID = mappedStatement.getId();
            PPage page = null;
            page = PageContext.getContext().getSession(RequestUtil.getlogserialnumber() + sqlID);
            if(page != null && page.isPagination()) {
                this.setDialect();
                Object parameter = invocation.getArgs()[1];
                BoundSql boundSql = mappedStatement.getBoundSql(parameter);
                String originalSql = boundSql.getSql().trim();
                String originalSqlCount = originalSql;
                if(page.getSort() != null && !"".equals(page.getSort())) {
                    originalSql = this.dialect.getOrderByString(originalSql, page.getSort(), page.getOrder() == null?"asc":page.getOrder());
                }

                originalSql = originalSql.trim();
                RowBounds rowBounds = (RowBounds)invocation.getArgs()[2];
                Object parameterObject = boundSql.getParameterObject();
                if(boundSql != null && boundSql.getSql() != null && !"".equals(boundSql.getSql())) {
                    Connection connection = null;
                    ResultSet rs = null;
                    PreparedStatement countStmt = null;
                    Long total = Long.valueOf(page.getTotals());
                    BoundSql countBS;
                    if(total.longValue() == 0L) {
                        StringBuffer countSql = null;

                        try {
                            countSql = new StringBuffer(originalSql.length() + 100);
                            countSql.append("select count(1) from (").append(originalSqlCount).append(") t");
                            if("DB2".equals(InitParamUtil.getDatabaseInfoName())) {
                                countSql.append(" with ur");
                            }

                            connection = mappedStatement.getConfiguration().getEnvironment().getDataSource().getConnection();
                            countStmt = connection.prepareStatement(countSql.toString());
                            countBS = new BoundSql(mappedStatement.getConfiguration(), countSql.toString(), boundSql.getParameterMappings(), parameterObject);
                            this.setParameters(countStmt, mappedStatement, countBS, parameterObject);
                            rs = countStmt.executeQuery();
                            if(rs.next()) {
                                total = Long.valueOf(rs.getLong(1));
                            }

                            page.setTotals(total.longValue());
                        } catch (Exception var20) {
                            logger.error("获取分页总数异常" + var20.toString() + ",sql=" + countSql);
                        } finally {
                            rs.close();
                            countStmt.close();
                            connection.close();
                        }
                    }

                    if(rowBounds == null || rowBounds == RowBounds.DEFAULT) {
                        rowBounds = new RowBounds(page.getRows() * (page.getPage() - 1), page.getRows());
                    }

                    String pagesql = this.dialect.getLimitString(originalSql, rowBounds.getOffset(), rowBounds.getLimit());
                    invocation.getArgs()[2] = new RowBounds(0, 2147483647);
                    countBS = new BoundSql(mappedStatement.getConfiguration(), pagesql, boundSql.getParameterMappings(), boundSql.getParameterObject());
                    MappedStatement newMs = this.copyFromMappedStatement(mappedStatement, new PaginationInterceptor.BoundSqlSqlSource(countBS));
                    invocation.getArgs()[0] = newMs;
                    return invocation.proceed();
                } else {
                    return null;
                }
            } else {
                return invocation.proceed();
            }
        }
    }

    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    public void setProperties(Properties properties) {
    }

    private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException {
        ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        if(parameterMappings != null) {
            Configuration configuration = mappedStatement.getConfiguration();
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            MetaObject metaObject = parameterObject == null?null:configuration.newMetaObject(parameterObject);

            for(int i = 0; i < parameterMappings.size(); ++i) {
                ParameterMapping parameterMapping = (ParameterMapping)parameterMappings.get(i);
                if(parameterMapping.getMode() != ParameterMode.OUT) {
                    String propertyName = parameterMapping.getProperty();
                    PropertyTokenizer prop = new PropertyTokenizer(propertyName);
                    Object value;
                    if(parameterObject == null) {
                        value = null;
                    } else if(typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                        value = parameterObject;
                    } else if(boundSql.hasAdditionalParameter(propertyName)) {
                        value = boundSql.getAdditionalParameter(propertyName);
                    } else if(propertyName.startsWith("__frch_") && boundSql.hasAdditionalParameter(prop.getName())) {
                        value = boundSql.getAdditionalParameter(prop.getName());
                        if(value != null) {
                            value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));
                        }
                    } else {
                        value = metaObject == null?null:metaObject.getValue(propertyName);
                    }

                    TypeHandler typeHandler = parameterMapping.getTypeHandler();
                    if(typeHandler == null) {
                        throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId());
                    }

                    typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
                }
            }
        }

    }

    private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
        Builder builder = new Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.cache(ms.getCache());
        MappedStatement newMs = builder.build();
        return newMs;
    }

    public static class BoundSqlSqlSource implements SqlSource {
        BoundSql boundSql;

        public BoundSqlSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        public BoundSql getBoundSql(Object parameterObject) {
            return this.boundSql;
        }
    }
}
